﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Babushka.GameModels.Tiles;

namespace Babushka.GameModels
{
    class Level
    {
        public bool DrawExtraInformation { get; set; }
        private int[,] _tiles;
        private List<Tuple<Texture2D, Vector2>> _backImages;
        public int MapWidth
        {
            get
            {
                return _tiles.GetLength(0);
            }
        }
        public int MapHeight 
        { 
            get 
            { 
                return _tiles.GetLength(1); 
            } 
        }
        public Tile this[int x, int y]
        {
            get
            {
                if (x >= this.MapWidth || x < 0 ||
                    y >= MapHeight || y < 0)
                    throw new ArgumentOutOfRangeException();
                if (_tiles[x, y] < 0 || _tiles[x, y] >= Tile.Tiles.Count)
                    return null;

                return Tile.Tiles[_tiles[x, y]];
            }
            set
            {
                if (x >= this.MapWidth || x < 0 ||
                    y >= MapHeight || y < 0)
                    throw new ArgumentOutOfRangeException();
                if (value == null)
                    _tiles[x, y] = -1;
                _tiles[x, y] = Tile.GetID(value);
            }
        }

        public Level(int width, int height)
        {
            this._tiles = new int[width, height];
            for (int x = 0; x < MapWidth; x++)
            {
                for (int y = 0; y < MapHeight; y++)
                {
                    this[x, y] = null;
                }
            }
        }

        public void Update()
        {
            
        }
        public void Draw()
        {
            foreach (var image in _backImages)
                Game1.SpriteBatch.Draw(image.Item1, image.Item2, Color.White);

            for (int x = 0; x < MapWidth; x++)
                for (int y = 0; y < MapHeight; y++)
                    Tile.Tiles[_tiles[x, y]].DrawTile(x, y);
            if (DrawExtraInformation)
            {
                //TODO: Debug info
                //Draw level name and stuff.
            }
        }
        public string LevelName { get; set; }

        public static void SaveLevel(Level lvl, string filePath)
        {
            BinaryFormatter formatter = new BinaryFormatter();
            formatter.Serialize(File.Create(filePath), lvl);
        }
        public static Level LoadLevel(string filePath)
        {
            BinaryFormatter formatter = new BinaryFormatter();
            return formatter.Deserialize(File.Open(filePath, FileMode.Open)) as Level;
        }
    }
}
